//
//  RSSParser.m
//  tv3rss
//
//  Created by Job Search on 01/08/14.
//  Copyright (c) 2014 responsfabrikken. All rights reserved.
//

#import "RSSParser.h"

@implementation RSSParser

    @synthesize item, items, currentElementValue;

- (RSSParser *) initXMLParserWithUrl : (NSURL * ) url {
    self = [super init];
    
    item    = [[RSSItemCustom alloc] init];
    items   = [[NSMutableArray alloc] init];
    currentElementValue = [[NSMutableString alloc] init];
    
     NSXMLParser *nsXmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
    [nsXmlParser setDelegate:self];
    BOOL success = [nsXmlParser parse];
    
    if (success) {
        NSLog(@"No errors - user count : %lu", (unsigned long)[items count]);
    } else {
        NSLog(@"Error parsing document!");
    }
    
    return self;
    
}



- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict {
    if ([item isTagName:elementName]) {
       item = [[RSSItemCustom alloc] init];
    }
}


- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
   // if (!currentElementValue) {
   //     currentElementValue = [[NSMutableString alloc] initWithString:string];
   // } else {
        [currentElementValue appendString:string];
   // }
}


- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    
    if ([item isTagName:elementName]) {
        [items addObject:item];
    } else {
        if([item containsElementName:elementName]){
            //trim the value a bit....
                NSString *trimedValue = [[self.currentElementValue stringByReplacingOccurrencesOfString:@"\n" withString:@""]stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
            
            [item setValue:trimedValue forKey:elementName];
        }
    }
    
    [currentElementValue setString:@""];
}

- (void)parserDidEndDocument:(NSXMLParser *)parser {
    return;
}

@end
